import Cookies from 'js-cookie'

const tokenKey = 'wr-token'
const userKey = 'wr-user'

export function cookieExists(name) {
    return Cookies.get(name) !== undefined
}

export function getCookie(name) {
    return Cookies.get(name)
}

export function setCookie(name, value) {
    return Cookies.set(name, value)
}

export function removeCookie(name) {
    return Cookies.remove(name)
}

export function getToken() {
    // 先去localStorage取token，没有再去cookie取
    const token = localStorage.getItem(tokenKey);
    if (token) {
        setCookie(tokenKey, token);
    }
    return Cookies.get(tokenKey)
}

export function setToken(token, userName) {
    if (token) {
        localStorage.setItem(tokenKey, token);
        // 保存用户名
        localStorage.setItem(userKey, userName);
    }
    return Cookies.set(tokenKey, token)
}

export function removeToken() {
    localStorage.removeItem(tokenKey);
    localStorage.removeItem(userKey)
    return Cookies.remove(tokenKey)
}